package com.soft.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soft.entity.KanbanItem;
import com.soft.entity.Schedule;
import com.soft.entity.User;
import com.soft.mapper.KanbanItemMapper;
import com.soft.mapper.ScheduleMapper;
import com.soft.mapper.TeamMapper;
import com.soft.mapper.UserMapper;
import com.soft.service.MetricsService;
import com.soft.service.TeamService;
import com.soft.service.UserService;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 团队指标接口（/team-metrics）：
 * - /overview 与 /my-teams：登录用户可用，统计其作为 leader/创建者相关团队数据
 * - /managed-schedules：列出所管理团队的日程（可按状态过滤）
 * - /company-kanban、/company-task-updates：公司层级数据（需用户 active）
 */
@RestController
@RequestMapping("/team-metrics")
public class TeamMetricsController {
    private static final Logger log = LoggerFactory.getLogger(TeamMetricsController.class);

    @Autowired
    private MetricsService metricsService;

    @Autowired
    private UserService userService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Autowired
    private KanbanItemMapper kanbanItemMapper;

    private Integer currentUserId(HttpServletRequest req) {
    // 从头部获取当前用户ID（演示用伪鉴权）
    if (req == null) return null;
    String h = req.getHeader("X-User-Id");
    if (h == null || h.isEmpty()) return null;
    try { return Integer.valueOf(h); } catch (NumberFormatException ex) { return null; }
    }

    private boolean isTeamLeaderOrMember(HttpServletRequest req) {
    // 要求用户处于 active 状态（简化权限判定）
    Integer uid = currentUserId(req);
    if (uid == null) return false;
    User u = userService.getById(uid);
    return u != null && u.getStatus() != null && "active".equalsIgnoreCase(u.getStatus());
    }

    /**
     * 团队概况查询接口 - 适用于团队leader和普通用户
     * 返回用户作为leader的团队或创建的团队的统计数据
     */
    @GetMapping("/overview")
    public ResponseEntity<?> teamOverview(@RequestParam(value = "days", required = false, defaultValue = "7") Integer days,
                                         HttpServletRequest req) {
        try {
            // 1) 未登录直接拒绝
            Integer uid = currentUserId(req);
            if (uid == null) {
                return ResponseEntity.status(401).body("unauthorized");
            }
            // 2) 要求 active 用户
            if (!isTeamLeaderOrMember(req)) {
                return ResponseEntity.status(403).body("user not active");
            }
            // 3) 统一的下限保护与查询
            Map<String, Object> data = metricsService.leaderMetrics(uid, days != null ? Math.max(1, days) : 7);
            return ResponseEntity.ok(data);
        } catch (Exception e) {
            log.error("/team-metrics/overview error", e);
            return ResponseEntity.status(500).body("team overview failed: " + e.getMessage());
        }
    }

    /**
     * 获取用户的团队概况 - 更宽松的权限控制
     * 任何登录用户都可以查看自己相关的团队数据
     */
    @GetMapping("/my-teams")
    public ResponseEntity<?> myTeamsOverview(@RequestParam(value = "days", required = false, defaultValue = "7") Integer days,
                                            HttpServletRequest req) {
        try {
            // 1) 登录校验
            Integer uid = currentUserId(req);
            if (uid == null) {
                return ResponseEntity.status(401).body("unauthorized");
            }
            // 2) 查询团队数据（同 leaderMetrics）
            Map<String, Object> data = metricsService.leaderMetrics(uid, days != null ? Math.max(1, days) : 7);
            return ResponseEntity.ok(data);
        } catch (Exception e) {
            log.error("/team-metrics/my-teams error", e);
            return ResponseEntity.status(500).body("my teams overview failed: " + e.getMessage());
        }
    }

    /**
     * 获取所有管理团队的日程
     * 返回用户作为leader的所有团队的日程信息
     */
    @GetMapping("/managed-schedules")
    public ResponseEntity<?> getManagedTeamSchedules(@RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit,
                                                    @RequestParam(value = "status", required = false) String status,
                                                    HttpServletRequest req) {
        try {
            // 1) 登录与状态校验
            Integer uid = currentUserId(req);
            if (uid == null) { return ResponseEntity.status(401).body("unauthorized"); }
            if (!isTeamLeaderOrMember(req)) { return ResponseEntity.status(403).body("user not active"); }
            // 2) 获取用户管理的所有团队
            List<Map<String, Object>> managedTeams = teamMapper.getTeamsByLeaderOrCreator(uid);
            
            List<Map<String, Object>> allSchedules = new ArrayList<>();
            
            for (Map<String, Object> team : managedTeams) {
                Integer teamId = (Integer) team.get("teamId");
                
                // 3) 获取团队的日程（可按状态过滤、限制数量）
                QueryWrapper<Schedule> qw = new QueryWrapper<>();
                qw.eq("team_id", teamId);
                if (status != null && !status.isEmpty()) {
                    qw.eq("status", status);
                }
                qw.orderByDesc("create_time");
                qw.last("LIMIT " + limit);
                List<Schedule> teamSchedules = scheduleMapper.selectList(qw);
                
                // 4) 组装包含详情的 Map 结构
                for (Schedule schedule : teamSchedules) {
                    Map<String, Object> scheduleInfo = new HashMap<>();
                    scheduleInfo.put("scheduleId", schedule.getScheduleId());
                    scheduleInfo.put("title", schedule.getTitle());
                    scheduleInfo.put("content", schedule.getContent());
                    scheduleInfo.put("startTime", schedule.getStartTime());
                    scheduleInfo.put("endTime", schedule.getEndTime());
                    scheduleInfo.put("location", schedule.getLocation());
                    scheduleInfo.put("status", schedule.getStatus());
                    scheduleInfo.put("priority", schedule.getPriority());
                    scheduleInfo.put("createTime", schedule.getCreateTime());
                    scheduleInfo.put("updateTime", schedule.getUpdateTime());
                    scheduleInfo.put("remindTime", schedule.getRemindTime());
                    scheduleInfo.put("creatorId", schedule.getCreatorId());
                    scheduleInfo.put("teamId", schedule.getTeamId());
                    scheduleInfo.put("teamName", team.get("teamName"));
                    
            // 5) 追加创建者姓名（捕获异常避免影响整体）
                    if (schedule.getCreatorId() != null) {
                        try {
                            User creator = userMapper.getUserById(schedule.getCreatorId());
                            if (creator != null) {
                                scheduleInfo.put("creatorName", creator.getUsername());
                            } else {
                                scheduleInfo.put("creatorName", "未知用户");
                            }
                        } catch (Exception e) {
                            scheduleInfo.put("creatorName", "未知用户");
                        }
                    } else {
                        scheduleInfo.put("creatorName", "未知用户");
                    }
                    
            // 6) 追加指派人信息（如存在看板项）
                    try {
                        QueryWrapper<KanbanItem> kanbanQw = new QueryWrapper<>();
                        kanbanQw.eq("schedule_id", schedule.getScheduleId());
                        KanbanItem kanbanItem = kanbanItemMapper.selectOne(kanbanQw);
                        
                        if (kanbanItem != null && kanbanItem.getAssigneeId() != null) {
                            User assignee = userMapper.getUserById(kanbanItem.getAssigneeId());
                            if (assignee != null) {
                                scheduleInfo.put("assigneeName", assignee.getNickname());
                                scheduleInfo.put("assigneeId", kanbanItem.getAssigneeId());
                            } else {
                                scheduleInfo.put("assigneeName", "暂无");
                                scheduleInfo.put("assigneeId", null);
                            }
                        } else {
                            scheduleInfo.put("assigneeName", "暂无");
                            scheduleInfo.put("assigneeId", null);
                        }
                    } catch (Exception e) {
                        scheduleInfo.put("assigneeName", "暂无");
                        scheduleInfo.put("assigneeId", null);
                    }
                    
                    allSchedules.add(scheduleInfo);
                }
            }
            
        // 7) 按创建时间倒序排序
            allSchedules.sort((a, b) -> {
                java.time.LocalDateTime timeA = (java.time.LocalDateTime) a.get("createTime");
                java.time.LocalDateTime timeB = (java.time.LocalDateTime) b.get("createTime");
                if (timeA == null && timeB == null) return 0;
                if (timeA == null) return 1;
                if (timeB == null) return -1;
                return timeB.compareTo(timeA);
            });
            
        // 8) 限制返回数量
            if (allSchedules.size() > limit) {
                allSchedules = allSchedules.subList(0, limit);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("schedules", allSchedules);
            result.put("total", allSchedules.size());
            result.put("managedTeamsCount", managedTeams.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("/team-metrics/managed-schedules error", e);
            return ResponseEntity.status(500).body("get managed schedules failed: " + e.getMessage());
        }
    }

    /**
     * 获取公司看板数据 - 管理员专用接口
     * 返回全公司的看板统计信息
     */
    @GetMapping("/company-kanban")
    public ResponseEntity<?> getCompanyKanban(HttpServletRequest req) {
        try {
            // 1) 登录与状态校验
            Integer uid = currentUserId(req);
            if (uid == null) { return ResponseEntity.status(401).body("unauthorized"); }
            if (!isTeamLeaderOrMember(req)) { return ResponseEntity.status(403).body("user not active"); }
            // 2) 调用MetricsService获取公司看板数据
            Map<String, Object> kanbanData = metricsService.getCompanyKanbanData();
            return ResponseEntity.ok(kanbanData);
        } catch (Exception e) {
            log.error("/team-metrics/company-kanban error", e);
            return ResponseEntity.status(500).body("get company kanban failed: " + e.getMessage());
        }
    }

    /**
     * 获取公司级别的任务更新记录
     * @param limit 返回记录数量限制，默认20条
     * @return 任务更新记录列表
     */
    @GetMapping("/company-task-updates")
    public ResponseEntity<?> getCompanyTaskUpdates(
            @RequestParam(value = "limit", defaultValue = "20") Integer limit,
            HttpServletRequest req) {
        try {
            // 1) 登录与状态校验
            Integer uid = currentUserId(req);
            if (uid == null) { return ResponseEntity.status(401).body("unauthorized"); }
            if (!isTeamLeaderOrMember(req)) { return ResponseEntity.status(403).body("user not active"); }
            // 2) 获取公司级任务更新
            Map<String, Object> taskUpdates = metricsService.getCompanyTaskUpdates(limit);
            return ResponseEntity.ok(taskUpdates);
        } catch (Exception e) {
            log.error("/team-metrics/company-task-updates error", e);
            return ResponseEntity.status(500).body("get company task updates failed: " + e.getMessage());
        }
    }
}